/*
 * @(#)SubStringTag.java $version 2011. 10. 14
 * 
 * Copyright 2011 NHN Corp. All rights Reserved.
 * NHN PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
 */
package com.hangame.mbl.taglibs;

import javax.servlet.jsp.JspException;
import javax.servlet.jsp.tagext.TagSupport;

import org.apache.commons.lang.StringEscapeUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.hangame.common.taglibs.util.TagUtils;

// TODO: Auto-generated Javadoc
/**
 * The Class SubStringTag.
 * 
 * @author Lixing
 */
@SuppressWarnings("serial")
public class SubStringTag extends TagSupport {
	
	/** The Constant LOG. */
	private static final Log LOG = LogFactory.getLog(SubStringTag.class);
	
	/** The source. */
	private String source = null;
	
	/** The size. */
	private int size = 0;
	
	/** The mark. */
	private String mark = "..";
	
	/**
	 * Sets the source.
	 * 
	 * @param source the new source
	 */
	public void setSource(String source) {
		this.source = source;
	}
	
	/**
	 * Sets the mark.
	 * 
	 * @param mark the new mark
	 */
	public void setMark(String mark) {
		this.mark = mark;
	}
	
	/**
	 * Sets the size.
	 * 
	 * @param size the new size
	 */
	public void setSize(int size) {
		this.size = size;
	}
	
	/* (non-Javadoc)
	 * @see javax.servlet.jsp.tagext.TagSupport#doEndTag()
	 */
	@Override
	public int doEndTag() throws JspException {
		try {
			if (source != null) {
				source = getString(source, size);
				TagUtils.write(pageContext, source);
			}
		} catch (Exception e) {
			LOG.debug("### SubStringTag Exception :" + e);
			TagUtils.write(pageContext, "");
		}
		return EVAL_PAGE;
	}
	
	/**
	 * Gets the string.
	 * 
	 * @param value the value
	 * @param cut the cut
	 * @return the string
	 */
	private String getString(String value, int cut) {
		String str = StringEscapeUtils.unescapeHtml(value);
		if (cut <= 0) {
			return str;
		}
		int limit = cut;
		StringBuffer result = new StringBuffer(limit + mark.length());
		int chatAt = 0;
		int size = 0;
		for (int length = str.length(); chatAt < length; chatAt++) {
			char temp = str.charAt(chatAt);
			size += temp <= '\377' ? 1 : 2;
			if (size > limit) {
				break;
			}
			result.append(temp);
		}

		result = chatAt >= str.length() ? result : result.append(mark);
		return result.toString();
	}
}
